import re
import subprocess
import time
import os


class ADBManager:
    def __init__(self, device_id=None):
        self.device_id = device_id

    def run_adb_command(self, command):
        """执行ADB命令"""
        full_command = ["adb"]
        if self.device_id and command[0] not in ["start-server", "kill-server"]:
            full_command.extend(["-s", self.device_id])
        full_command.extend(command)

        print(f"Executing: {' '.join(full_command)}")
        try:
            result = subprocess.run(full_command, capture_output=True, text=True, encoding="utf-8")
            return result
        except subprocess.CalledProcessError as e:
            print(f"Error executing command: {e}")
            return None

    # ======================================================
    # 🔹 新增方法：ADB服务控制
    # ======================================================
    def start_server(self):
        """启动ADB服务"""
        print("Starting ADB server...")
        result = self.run_adb_command(["start-server"])
        if result is not None:
            print(result.stdout)
            print(result.stderr)
        else:
            print("Failed to start ADB server.")

    def kill_server(self):
        """停止ADB服务"""
        print("Killing ADB server...")
        result = self.run_adb_command(["kill-server"])
        if result is not None:
            print(result.stdout)
            print(result.stderr)
        else:
            print("Failed to kill ADB server.")

    # ======================================================

    def root_device(self):
        """Root设备并设置环境"""
        print("Step 1: Rooting device...")
        commands = [
            ["wait-for-device", "shell", "setprop", "service.dev.mode", "1"],
            ["wait-for-device", "remount"],
        ]

        for cmd in commands:
            res = self.run_adb_command(cmd)
            print(res.stdout)
            print(res.stderr)

    def start_data_collection(self):
        """开始数据采集"""
        print("Step 2: Starting data collection...")
        self.run_adb_command(["wait-for-device"])
        self.run_adb_command(["root"])
        self.run_adb_command(["shell", "dumpsys", "-t", "120", "android.yvr.trackingservice", "--dump_dataset", "5"])

    def stop_data_collection(self):
        """停止数据采集"""
        print("Step 4: Stopping data collection...")
        self.run_adb_command(["wait-for-device"])
        self.run_adb_command(["root"])
        self.run_adb_command(["shell", "dumpsys", "-t", "120", "android.yvr.trackingservice", "--dump_dataset", "0"])

    def wait_for_collection(self, collect_time):
        """等待采集完成"""
        print(f"Step 3: Collecting data for {collect_time} seconds...")
        time.sleep(collect_time)

    def pull_datasets(self):
        """拉取数据集"""
        print("Step 5: Pulling datasets...")

        datasets = [
            "ServiceDataLoggerRecord",
        ]

        for dataset_name in datasets:
            self._pull_single_dataset(dataset_name)

    def _pull_single_dataset(self, dataset_name):
        """拉取单个数据集"""
        print(f"Pulling {dataset_name}...")

        src_folder = f"/sdcard/{dataset_name}"
        # self._rm_pc_folder(dataset_name)
        self._pull_folder(src_folder)
        self._rm_mobile_folder(src_folder)

    def _rm_mobile_folder(self, folder):
        """删除移动端文件夹"""
        print(f"Delete {folder} from mobile")
        self.run_adb_command(["wait-for-device"])
        self.run_adb_command(["shell", "rm", "-rf", folder])

    def _rm_pc_folder(self, folder):
        """删除PC端文件夹"""
        print(f"Delete local {folder}")
        if os.path.exists(folder):
            import shutil
            shutil.rmtree(folder)

    def _pull_folder(self, folder):
        """拉取文件夹"""
        print(f"Pull {folder}")
        self.run_adb_command(["wait-for-device"])
        self.run_adb_command(["pull", folder, r"files/hand/data"])
        # self.run_adb_command(["pull", folder])

    def collect_data(self, collect_time):
        """运行完整的数据采集流程"""
        print(f"Starting data collection for {collect_time} seconds...")

        try:
            self.start_server()
            self.root_device()
            self.start_data_collection()
            self.wait_for_collection(collect_time)
            self.stop_data_collection()
            self.pull_datasets()

            print("Data collection completed!")
            return True

        except Exception as e:
            print(f"Error during data collection: {e}")
            return False

    def test_delay(self):
        self.root_device()
        print(f"Testing delay...")
        self.run_adb_command(["wait-for-device"])
        self.run_adb_command(["push", r"files/hand/lib/demo", r"/vendor/bin/demo"])
        self.run_adb_command(["push", r"files/hand/lib/libHandTracking.so", r"/vendor/yvr/lib64/libHandTracking.so"])
        self.run_adb_command(["shell", "chmod", "+x", "/vendor/bin/demo"])

        try:
            # 运行demo并捕获输出
            result = self.run_adb_command(["shell", "LD_LIBRARY_PATH=/vendor/yvr/lib64", "/vendor/bin/demo"])
            if not result:
                print("Demo执行无输出")
                return 0.0
            result = result.stdout.strip()

            # 从输出中提取所有时间值（微秒）
            # 支持多种可能的格式变体
            time_patterns = [
                r'追踪执行时间:\s*(\d+)\s*微秒',
            ]

            times_microseconds = []
            for pattern in time_patterns:
                matches = re.findall(pattern, result, re.IGNORECASE)
                if matches:
                    times_microseconds.extend([int(match) for match in matches])

            if not times_microseconds:
                print("无法提取时间数据")
                return 0.0

            # 计算平均时间（微秒）
            avg_microseconds = sum(times_microseconds) / len(times_microseconds)

            # 转换为毫秒
            avg_milliseconds = avg_microseconds / 1000.0

            # 计算其他统计信息
            min_time = min(times_microseconds) / 1000.0
            max_time = max(times_microseconds) / 1000.0

            print(f"找到 {len(times_microseconds)} 个时间数据点")
            print(f"时间范围: {min_time:.2f} - {max_time:.2f} 毫秒")
            print(f"平均延迟: {avg_milliseconds:.2f} 毫秒")

            return float(avg_milliseconds)

        except Exception as e:
            print(f"测试延迟时发生错误: {e}")
            return 0.0


if __name__ == "__main__":
    adb = ADBManager()
    adb.test_delay()